import pandas as pd
import plotly.express as px
from datetime import datetime

# === 设置真实周期（单位：天） ===
true_period = 0.394

# === 加载 CSV 数据文件 ===
file_path = "/mnt/7b21f1e1-eb25-4cd5-bdb5-06d7d82fa253/Temp/force_photmetry/result50cm/asteroid_photometry_results.csv"
df = pd.read_csv(file_path)

# === 函数：准备指定波段的数据 ===
def prepare_band(df, band):
    df_band = df[(df['band'] == band) & (df['calmag'].notna())].copy()
    df_band['timestamp'] = pd.to_datetime(df_band['obs_time'])
    df_band['mjd'] = (df_band['timestamp'] - df_band['timestamp'].min()).dt.total_seconds() / 86400.0
    df_band['phase'] = (df_band['mjd'] / true_period) % 1

    # === 显示：文件名、时间、星等 ± 误差 ===
    df_band['hover_info'] = df_band.apply(
        lambda row: f"file: {row['fn']}<br>time: {row['obs_time']}<br>mag: {row['calmag']:.3f} ± {row['magerr']:.3f}",
        axis=1
    )
    return df_band

# === 处理 g 和 r 波段 ===
df_r = prepare_band(df, 'r')
df_g = prepare_band(df, 'g')

# === r 波段相位图 ===
fig_r = px.scatter(
    df_r, x='phase', y='calmag', error_y='magerr',
    hover_data=['hover_info'], title=f"r-band Folded Light Curve (P = {true_period} days)",
    labels={'calmag': 'Magnitude', 'phase': 'Phase'},
    color_discrete_sequence=['red']
)
fig_r.update_yaxes(autorange="reversed")
fig_r.update_traces(marker=dict(size=6, opacity=0.8), hovertemplate="%{customdata[0]}")
fig_r.write_html("lightcurve_r.html")

# === g 波段相位图 ===
fig_g = px.scatter(
    df_g, x='phase', y='calmag', error_y='magerr',
    hover_data=['hover_info'], title=f"g-band Folded Light Curve (P = {true_period} days)",
    labels={'calmag': 'Magnitude', 'phase': 'Phase'},
    color_discrete_sequence=['green']
)
fig_g.update_yaxes(autorange="reversed")
fig_g.update_traces(marker=dict(size=6, opacity=0.8), hovertemplate="%{customdata[0]}")
fig_g.write_html("lightcurve_g.html")
